﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Infancy.Core.Entities;
using Infancy.Core.Service;
using Infancy.Data;
using Infancy.Service;

namespace Infancy.Service.Impls {
    public class ForumService : CachedServiceBase,IForumService {
        private static IList<Forum> _cache;
        private static object _synlock = new object();

        #region IForumService Members

        public IList<Forum> GetList() {
            if (_cache == null) {
                lock (_synlock) {
                    if (_cache == null) {
                        IForumRepository forumRepository = LoadRepository<IForumRepository>();
                        _cache = forumRepository.GetList();
                    }
                }
            }
            return _cache;
        }

        public IList<Forum> GetListByForumId(long forumId) {
            return GetList().Where(f => f.ParentId == forumId).ToList();
        }

        public Forum GetById(long forumId) {
            return GetList().FirstOrDefault(f => f.Id == forumId);
        }

        public Forum GetByName(string name) {
            return GetList().FirstOrDefault(f => f.Name.Equals(name));
        }

        public void Save(Forum forum) {
            IForumRepository forumRepository = LoadRepository<IForumRepository>();
            if (forum.Id > 0) {
                forumRepository.Update(forum);
            } else {
                forumRepository.Insert(forum);
            }
            ClearCache();
        }

        public override void ClearCache() {
            _cache = null;
        }

        #endregion
    }
}
